import { Route, Routes } from "react-router-dom";

import "@/assets/styles/global.scss";
import { ConfigProvider, theme } from "antd";
import { useAppDispatch, useAppSelector } from "@/store/hook.ts";
import { useNavigate } from "react-router-dom";
import { RouteConfig, routers } from "@/router/index.tsx";
import AuthRoute from "@/router/AuthRouter.tsx";
import { ReactNode } from "react";

import { changeLoginState } from "@/store/modules/loginStore";

function App() {
  const token = localStorage.getItem("blogToken") || "";
  const dispatch = useAppDispatch();
  const themeColor = useAppSelector((state) => state.theme.themeColor);

  if (token !== "") {
    dispatch(changeLoginState(true));
    // console.log(loginState, "loginState1");
  }


  const RouteAuthFun = (routeList: RouteConfig[]) => {
    return routeList.map(
      (item: {
        path: string;
        auth: boolean;
        element: ReactNode;
        children?: RouteConfig[];
      }) => {
        return (
          <Route
            path={item.path}
            element={
              <AuthRoute auth={item.auth} key={item.path}>
                {item.element}
              </AuthRoute>
            }
            key={item.path}
          >
            {/* 递归调用，因为可能存在多级的路由 */}
            {item?.children && RouteAuthFun(item.children)}
          </Route>
        );
      }
    );
  };

  return (
    <>
      <ConfigProvider
        theme={{ algorithm: themeColor ? theme.darkAlgorithm : undefined }}
      >
        <Routes>{RouteAuthFun(routers)}</Routes>
      </ConfigProvider>
    </>
  );
}

export default App;
